package com.cskaoyan.user.controller;

import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.user.bo.RegisterBo;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dto.KaptchaCodeRequest;
import com.cskaoyan.user.dto.KaptchaCodeResponse;
import com.cskaoyan.user.dto.UserRegisterRequest;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.IRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 创建日期: 2022/05/18 22:23
 *
 * @author JinLu Zhou
 */
@RestController
@RequestMapping("/user")
public class RegisterController {

    @Autowired
    IKaptchaService iKaptchaService;
    @Autowired
    IRegisterService iRegisterService;

    @RequestMapping("/register")
    public ResponseData register(@RequestBody RegisterBo registerBo, HttpServletRequest request) {
        String captcha = registerBo.getCaptcha();
        String email = registerBo.getEmail();
        String userName = registerBo.getUserName();
        String userPwd = registerBo.getUserPwd();

        //验证验证码
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String kaptcha_uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(kaptcha_uuid);
        kaptchaCodeRequest.setCode(captcha);
        KaptchaCodeResponse kaptchaCodeResponse = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        if (!kaptchaCodeResponse.getCode().equals(UserRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
        }

        //去向用户表插入记录
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setEmail(email);
        userRegisterRequest.setUserName(userName);
        userRegisterRequest.setUserPwd(userPwd);
        UserRegisterResponse response = iRegisterService.register(userRegisterRequest);
        if (response.getCode().equals(UserRetCode.SUCCESS.getCode())) {
            //注册成功
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }
}
